
import { Button, Space, Table, Select, message, Modal } from 'antd';
import ContentLayout from '@/layouts/ContentLayout'
import { useEffect } from 'react';
import { connect } from 'umi';
import UserBrief from '@/components/UserBrief';
import styles from './style.less'
import { useState } from 'react';
import Form from 'antd/es/form/Form';
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect';
import { saveUser, deleteUser } from '@/services/project/project'
const FormItem = Form.Item;




const ProjectUser = (props) => {
    const {
        dispatch,
        projectRoleList = [],
        userPage,
        projectId,
        projectPermission
    } = props

    const [addUserModalVisibla, setAddUserModalVisibla] = useState(false)
    const [initUser, setInitUser] = useState({})
    const [params, setParams] = useState({})
    const [userSelectParams, setUserSelectParams] = useState({})
    const [permission, setPermission] = useState({})

    const [form] = Form.useForm();

    useEffect(() => {
        if (projectId) {
            dispatch({
                type: 'enterprise/listProjectRole',
            })
            queryProjectList(params)
        }
    }, [projectId])

    useEffect(() => {
        setPermission({
            ...projectPermission?.member
        })
    }, [projectPermission])

    const hideAddUserModal = async () => {
        await setInitUser({})
        form.resetFields();
        setAddUserModalVisibla(false);
    };

    const queryProjectList = (newParams) => {
        dispatch({
            type: 'project/listUser',
            payload: {
                projectId: projectId,
                params: newParams
            }
        })
    }

    const onQueryChange = (params) => {
        setParams(params)
        queryProjectList(params)
    }

    const saveProjectUser = async () => {
        const values = await form.validateFields()
        saveUser(projectId, values).then(({ success }) => {
            if (success) {
                message.success("保存成功！");
                queryProjectList(params);
                hideAddUserModal()
            }
        })
    };

    const deleteProjectUser = (record) => {
        Modal.confirm({
            title: '删除项目用户',
            content: `确认删除用户：${record.user.nickName || record.user.username}`,
            okText: '确认',
            cancelText: '取消',
            onOk: (v) => {
                deleteUser(projectId, record.userId).then(({ success }) => {
                    if (success) {
                        message.success("删除成功！");
                        queryProjectList(params);
                    }
                })
                return Promise.resolve()
            }
        });

    }

    const tableColumns = [
        {
            title: '用户',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
            width: "20%",
            fixed: 'left',
            sorter: (a, b) => a.user.nickName.localeCompare(b.user.nickName),
            render: (text, record) => <UserBrief user={record.user}></UserBrief>,
        },
        {
            title: '项目角色',
            dataIndex: 'roleName',
            key: 'roleName',
            width: "20%",
            fixed: 'left',
            sorter: (a, b) => a.roleName.localeCompare(b.roleName),
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            width: "20%",
            fixed: 'left',
            render: (text, record) => (
                record.isOwner === 1 ? <>负责人</> :
                    (
                        <div className={styles.actionClass}>
                            <Button size="small" type="link" shape="round"
                                onClick={() => {
                                    setUserSelectParams({
                                        userId: record.userId
                                    })
                                    setInitUser(record)
                                    setAddUserModalVisibla(true)
                                }}
                            >修改</Button>
                            <Button size="small" danger type="text" shape="round"
                                onClick={() => {
                                    deleteProjectUser(record);
                                }}
                            >删除</Button>
                        </div>
                    )

            )
        }
    ]

    const queryItems = [
        {
            name: "inRoleId",
            label: "角色",
            isMain: true,
            type: "tagSelect",
            // expandable: true,
            options: [...projectRoleList].map((role) => {
                return {
                    value: role.id,
                    label: role.name
                }
            })
        }
    ]

    const actionHeader = [
        <Button type="primary" size="middle" onClick={() => {
            setUserSelectParams({
                notInUserId: userPage.list.map((user) => user.userId).join(",")
            })
            setAddUserModalVisibla(true)
        }}>
            新增
        </Button>
    ]


    return (
        <>
            <ContentLayout
                queryItems={queryItems}
                onQueryChange={onQueryChange}
                actionHeader={actionHeader}
                content={
                    <Table
                        columns={tableColumns}
                        pagination={false}
                        loading={!userPage}
                        dataSource={userPage && userPage.list}
                        rowKey="id"
                        size="small"
                        onRow={record => {
                            return {
                                onClick: () => {
                                }
                            }
                        }}
                    >
                    </Table>
                }
            >
            </ContentLayout>
            <Modal
                visible={addUserModalVisibla}
                closable
                title={"新增项目成员"}
                onCancel={() => {
                    hideAddUserModal()
                }}
                onOk={() => {
                    saveProjectUser();
                }}
                destroyOnClose
                okText={"确认"}
                cancelText={"取消"}
            >
                <Form
                    form={form}
                    initialValues={initUser}
                >
                    <FormItem
                        label={"用户"}
                        name="userId"
                        rules={[
                            {
                                required: true,
                                message: "请选择用户",
                            },
                        ]}
                    >
                        <EnterpriseUserSelect
                            disabled={!!initUser.userId}
                            params={userSelectParams} ></EnterpriseUserSelect>
                    </FormItem>
                    <FormItem label={"角色"}
                        name="roleId"
                        rules={[
                            {
                                required: true,
                                message: "请选择角色",
                            },
                        ]}
                    >
                        <Select placeholder="请选择角色" >
                            {projectRoleList.map((item) => (
                                <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                            ))}
                        </Select>
                    </FormItem>
                </Form>
            </Modal>
        </>
    )
}

export default connect(({ enterprise, project }) => ({
    projectRoleList: enterprise.projectRoleList,
    userPage: project.userPage
}))(ProjectUser);